import os
import shutil
import sys

resPath = sys.argv[1]

# ResourcePath = "/Users/pimingzhen/Works/Current/client-ftp-clear/iOS"

def findLatestBundleVer(resDir):
    latestVer = 0
    for root, dirs, files in os.walk(resDir):
        for f in files:
            fileName = os.path.splitext(f)[0]
            fileType = os.path.splitext(f)[1]
            if fileType == '.zip':
                
                latestVer = max(int(fileName), latestVer)
    return latestVer

def clearOldVerBundle(resDir, latestVer):
    for root, dirs, files in os.walk(resDir):
        for f in files:
            fileName = os.path.splitext(f)[0]
            fileType = os.path.splitext(f)[1]
            if fileType == '.zip':
                if latestVer == int(fileName):
                    print("Skip  :" + os.path.join(resDir, fileName))
                    print("Skip  :" + os.path.join(resDir, fileName + ".zip"))
                else:
                    try:
                        shutil.rmtree(os.path.join(resDir, fileName))
                        os.remove(os.path.join(resDir, fileName + ".zip")) 
                        print("delete:" + os.path.join(resDir, fileName))
                        print("delete:" + os.path.join(resDir, fileName + ".zip"))
                    except:
                        print("An exception occurred" + os.path.join(resDir, fileName))

    return latestVer

latestVer = findLatestBundleVer(resPath)
print("/app/client-ftp-clear/py/removeOldVersionBundle.py:" + str(latestVer))
clearOldVerBundle(resPath, latestVer)
